//
//  MembersShareController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/4/5.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//
#import <JavaScriptCore/JavaScriptCore.h>
#import "MembersShareController.h"
//controller
//vendor
#import "RDVTabBarController.h"
#import "HYActivityView.h"
#import "SendMessageToWXReq+requestWithTextOrMediaMessage.h"
#import "WXMediaMessage+messageConstruct.h"
//untils
#import "UIColor+Hex.h"
#import "UIImage+ColorToImage.h"
#import "AppDelegate.h"
#import "NSString+Conversion.h"
#import "RDVTabBarController.h"
#import "MTA.h"
#import "Global.h"
#import "MBProgressHUD.h"
#import "ManagerGlobeUntil.h"
#import "WXApi.h"
@interface MembersShareController ()<UIWebViewDelegate>
{
    /** 分享视图 */
    HYActivityView *_activityView;//更多弹出框
    ButtonView *_wxWeibo;//微信朋友圈
    ButtonView *_wxFriends;//微信好友
}
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) JSContext *jsContext;
@property (nonatomic,strong)NSMutableDictionary *dicData;
@end

@implementation MembersShareController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.title =@"会员分享";
    [self addBackNavItem];
    [self setUpSubView];
    [self setupShareView];
    self.jsContext = [[JSContext alloc] init];
        _dicData=[[NSMutableDictionary alloc]init];
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."inView:self.view];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setWebViewData];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"会员分享"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"会员分享"];
}
#pragma mark--获取WEB数据
-(void)setWebViewData
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    UserInfoModel *userModel = [[ManagerGlobeUntil sharedManager]getUserInfo];
    NSString *URLStr =[NSString stringWithFormat:@"%@user/share?SIGNATURE=%@&TOKEN=%@",baseServerUrl,[userDefaults objectForKey: Phone_Signature],userModel.token];    //    URLStr = [NSString stringWithFormat:@"%@ser/order/daily",baseServerUrl];
    NSURL  *url =[[NSURL alloc]initWithString:URLStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];
    
}
#pragma mark - UIWebViewDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
    self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    //    [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.zoom=0.34"];
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"异常信息：%@", exceptionValue);
    };
    [self getShareDate];
    
}
-(void)getShareDate
{
     [_dicData removeAllObjects];
     NSString * serviceDetail=[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getShareData()"]];
    NSString *requestTmp = [NSString stringWithString:serviceDetail];
    NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
    [_dicData addEntriesFromDictionary:[NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil]];
}
#pragma mark-- buttonClick
-(void)shareBtnClick
{
    if (!_activityView) {
        _activityView = [[HYActivityView alloc]initWithTitle:@"更多" referView:self.view];
        _activityView.bgColor = [UIColor colorWithHexString:@"e9e9e9"];
        _activityView.numberOfButtonPerLine = 3;
        _activityView.tabBarisShow = NO;
        //横屏会变成一行6个, 竖屏无法一行同时显示6个, 会自动使用默认一行4个的设置
        [_activityView addButtonView:_wxWeibo];
        [_activityView addButtonView:_wxFriends];
        
        
    }
    [_activityView show];
}
-(void)backBtnAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark--初始化控件
-(void)setUpSubView
{
    //初始化webView
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0,VIEW_WIDTH , VIEW_HEIGHT-64-49)];
    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    _webView.backgroundColor=[UIColor whiteColor];
    _webView.scalesPageToFit = NO;
    [self.view addSubview:_webView];
    
    //底部按钮
    UIButton *shareBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame=CGRectMake(0,  CGRectGetMaxY(self.webView.frame), VIEW_WIDTH,49);
    [shareBtn setTitle:@"点击分享给好友" forState:UIControlStateNormal];
    shareBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    UIImage *shareBtnImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#c52720"]
                                                      frame:CGRectMake(0, 0, CGRectGetWidth(shareBtn.bounds),
                                                                       CGRectGetHeight(shareBtn.bounds))];
    [shareBtn setBackgroundImage:shareBtnImage forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareBtn];

}
- (void)setupShareView {
    /*********************************************微信朋友圈分享****************************************/
    _wxWeibo = [[ButtonView alloc]initWithText:@"微信朋友圈" image:[UIImage imageNamed:@"friendsicon@2x"] handler:^(ButtonView *buttonView){
       
        NSLog(@"微信朋友圈");
        //网页数据
        if ([WXApi isWXAppInstalled]) {//已安装微信
            WXWebpageObject *ext = [WXWebpageObject object];
            ext.webpageUrl = [NSString stringTransformObject:[self.dicData objectForKey:@"link"]];
            WXMediaMessage *message = [WXMediaMessage messageWithTitle:[NSString stringTransformObject:[self.dicData objectForKey:@"title"]]
                                                           Description:[NSString stringTransformObject:[self.dicData objectForKey:@"desc"]]
                                                                Object:ext
                                                            MessageExt:nil
                                                         MessageAction:nil
                                                            ThumbImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringTransformObject:[self.dicData objectForKey:@"thumb"]]]]]                                                              MediaTag:@""];
            
            SendMessageToWXReq* req = [SendMessageToWXReq requestWithText:nil
                                                           OrMediaMessage:message
                                                                    bText:NO
                                                                  InScene:WXSceneTimeline];
            [WXApi sendReq:req];
        } else {//未安装微信
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"您还未安装微信" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
        }
        
    }];
    [_wxWeibo.imageButton setImage:[UIImage imageNamed:@"friendsiconpressdown@2x"] forState:UIControlStateHighlighted];
    
    
    /*********************************************微信好友分享****************************************/
    
    _wxFriends = [[ButtonView alloc]initWithText:@"微信好友" image:[UIImage imageNamed:@"weixinicon@2x"] handler:^(ButtonView *buttonView){
        if ([WXApi isWXAppInstalled]) {//已安装微信
            WXWebpageObject *ext = [WXWebpageObject object];
            ext.webpageUrl = [NSString stringTransformObject:[self.dicData objectForKey:@"link"]];;
            WXMediaMessage *message = [WXMediaMessage messageWithTitle:[NSString stringTransformObject:[self.dicData objectForKey:@"title"]]
                                                           Description:[NSString stringTransformObject:[self.dicData objectForKey:@"desc"]]
                                                                Object:ext
                                                            MessageExt:nil
                                                         MessageAction:nil
                                                            ThumbImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringTransformObject:[self.dicData objectForKey:@"thumb"]]]]]
                                                              MediaTag:@""];
            
            SendMessageToWXReq* req = [SendMessageToWXReq requestWithText:nil
                                                           OrMediaMessage:message
                                                                    bText:NO
                                                                  InScene:WXSceneSession];
            [WXApi sendReq:req];
        } else {//未安装微信
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"您还未安装微信" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
        }
        
        
    }];
    
    [_wxFriends.imageButton setImage:[UIImage imageNamed:@"weixiniconpressdown@2x"] forState:UIControlStateHighlighted];
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
